﻿using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;


public class SpritePrefabTool : Editor
{ 
    //在编辑器中可以直接点击该按钮
    [MenuItem("MyMenu/AtlasMaker")]
    private static void MakeAtlas()
    {  //根据Atlas目录结构，创建预制件
        //E:/Subject 4.6/UnityDemo/BaseScript/Assets/Atlas
        DirectoryInfo rootDirInfo = new DirectoryInfo(Application.dataPath + "/Atlas");
        foreach (DirectoryInfo dirInfo in rootDirInfo.GetDirectories())
        {
            //获取Atlas文件夹名称  在Resources中创建
            string dirPath = Application.dataPath + "/Resources/Sprite/" + dirInfo.Name;
            if (Directory.Exists(dirPath) == false)
                Directory.CreateDirectory(dirPath);

            //获取该目录下所有文件 以及所有子目录
            foreach (FileInfo file in dirInfo.GetFiles("*.jpg", SearchOption.AllDirectories))
                AtlasToResources(dirPath, file);

            foreach (FileInfo file in dirInfo.GetFiles("*.png", SearchOption.AllDirectories))
                AtlasToResources(dirPath, file);
        }
    }

    private static void AtlasToResources(string dirPath, FileInfo file)
    {
        //E:\\Subject 4.6\\UnityDemo\\BaseScript\\Assets\\Atlas\\2048\\0.png
        string allPath = file.FullName;
        string assetPath = allPath.Substring(allPath.IndexOf("Assets"));//Assets/Atlas/2048/0.png
        //仅仅在编辑器中可以找到  发布后不可以     
        Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite>(assetPath);
        GameObject go = new GameObject(sprite.name);
        go.AddComponent<SpriteRenderer>().sprite = sprite;

        allPath = dirPath + "/" + sprite.name + ".prefab";
        string prefabPath = allPath.Substring(allPath.IndexOf("Assets"));
        //Assets/Resources/Sprite/2048/0.prefab
        PrefabUtility.CreatePrefab(prefabPath, go);
        GameObject.DestroyImmediate(go);
    }
}
